﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.BO.DanhMuc;
using DHQGHN.DAL.BO.TDT;
using DHQGHN.DAL.Models.Admin;
using DHQGHN.DAL.Models.DanhMuc;
using DHQGHN.DAL.Models.QTHT;
using DHQGHN.DAL.ModelsUpload;
using WebMatrix.WebData;

namespace DHQGHN.Services.QTHT
{
    public class AdminService : IAdminService
    {
        //private AreaBO areaBO;
        private GroupBO groupBO;
        private CommonListBO commonListBO;
        private UserBO userBO;
        private ApplicationBO appBO;
        private EnumeratorBO enumeratorBO;
        private UserInGroupBO userInGroupBO;
        private ActionNameBO actionNameBO;
        private UserBO _UserBO;
        #region Constructors
        /// <summary>
        /// 
        /// </summary>

        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(AdminService));

        public AdminService()
        {
            //string connString = ConfigurationManager.ConnectionStrings["DHQGHN_TDT.ConnectionString"].ConnectionString;
            //areaBO = new AreaBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_TDT_CONNECTION_STRING);
            commonListBO = new CommonListBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_CONNECTION_STRING);
            userBO = new UserBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_ADMIN_CONNECTION_STRING);
            appBO = new ApplicationBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_ADMIN_CONNECTION_STRING);
            enumeratorBO = new EnumeratorBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_CONNECTION_STRING);
            groupBO = new GroupBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_ADMIN_CONNECTION_STRING);
            userInGroupBO = new UserInGroupBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_ADMIN_CONNECTION_STRING);
            actionNameBO = new ActionNameBO();
        }
        #endregion
        #region Service Methods
        //Register người dùng trên hệ thống. 
        public USER_GROUP_CREATE Register(USER_GROUP_CREATE user)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new USER_GROUP_CREATE();
                }
                else
                {
                    USER_GROUP_CREATE ret = user;
                    if (String.IsNullOrWhiteSpace(ret.UserName))
                    {
                        ret.ErrorCode = 1;
                        ret.ErrorMessage = Properties.Resources.MSG_LOGIN_USERNAME_EMPTY;
                        return ret;
                    }

                    if (WebSecurity.UserExists(ret.UserName))
                    {
                        ret.ErrorCode = 2;
                        ret.ErrorMessage = Properties.Resources.MSG_USERNAME_EXISTS;
                        return ret;
                    }
                    else
                    {
                        ret.ErrorCode = 200;
                    }
                    string res = WebSecurity.CreateUserAndAccount(ret.UserName, "123456qR@", new { ret.IsActive, ret.FullName }, false);
                    if (ret.ErrorCode == 200)
                    {
                        USER_GROUP_CREATE us = new USER_GROUP_CREATE();
                        us.UserName = user.UserName;
                        us.GroupCode = user.GroupCode;
                        bool flag = userInGroupBO.InsertUserIntoGroup(us);
                        if (flag)
                        {
                            ret.ErrorMessage = "SUCCESS";
                        }
                        else
                        {
                            ret.ErrorCode = -1;
                            ret.ErrorMessage = "ERROR";
                        }
                    }
                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }

        }
        //sủ dụng trên PM2
        public USER_GROUP_CREATE RegisterUser(USER_GROUP_CREATE user)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new USER_GROUP_CREATE();
                }
                else
                {
                    USER_GROUP_CREATE ret = user;
                    if (String.IsNullOrWhiteSpace(ret.UserName))
                    {
                        ret.ErrorCode = 1;
                        ret.ErrorMessage = Properties.Resources.MSG_LOGIN_USERNAME_EMPTY;
                        return ret;
                    }

                    ret.ErrorCode = 200;
                    userBO = new UserBO();
                    PasswordGenerator gp = new PasswordGenerator();
                    gp.Minimum = 2;
                    gp.Maximum = 4;
                    gp.Kytuso = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
                    string a = gp.Generate();

                    gp.Kytuso = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
                    string a1 = gp.Generate();

                    gp.Kytuso = "0123456789".ToCharArray();
                    string a2 = gp.Generate();

                    gp.Kytuso = "!@$^-_()".ToCharArray();
                    string a3 = gp.Generate();

                    string PassWord = a + a1 + a2 + a3;

                    ret.Password = PassWord;

                    bool result = userBO.RegisterUser(ret);

                    if (ret.ErrorCode == 200 && result)
                    {
                        bool flag = userInGroupBO.AddUserIntoGroup(ret);
                        if (flag == true)
                        {
                            ret.ErrorMessage = "SUCCESS";
                        }
                        else
                        {
                            ret.ErrorCode = -1;
                            ret.ErrorMessage = "ERROR";
                        }

                        bool sendmail = SendGmail(ret.Email, "Thông tin tài khoản", "UserName: " + ret.UserName + " -- Pass: " + ret.Password);
                        if (!sendmail)
                        {
                            ret.ErrorCode = -1;
                            ret.ErrorMessage = "ERROR";
                        }
                    }

                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        
        }

        public bool UpdateUser(USER_GROUP_CREATE user)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return false;
                }
                else
                {
                    userBO = new UserBO();
                    return userBO.UpdateUser(user);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private bool SendGmail(string emailTo, string subject, string body)
        {
            try
            {
                string userName = WebConfigurationManager.AppSettings["PFUserName"];
                string PassWord = WebConfigurationManager.AppSettings["PFPassWord"];
                string Gmail = WebConfigurationManager.AppSettings["PFGmail"];
                string SMTPServer = WebConfigurationManager.AppSettings["SMTPServer"];
                string SMTPPort = WebConfigurationManager.AppSettings["SMTPPort"];

                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(SMTPServer);

                mail.From = new MailAddress(Gmail); //sample@gmail.com
                mail.To.Add(emailTo);
                mail.Subject = subject;
                mail.Body = body;

                SmtpServer.Port = Convert.ToInt32(SMTPPort);
                SmtpServer.Credentials = new System.Net.NetworkCredential(userName, PassWord);
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                return true;
                //MessageBox.Show("mail Send");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                return false;
            }
        }

        public bool ChangePassUser(string PassWord, string UserName, string AppCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return false;
                }
                else
                {
                    USER_GROUP_CREATE ret = new USER_GROUP_CREATE();
                    ret.UserName = UserName;
                    ret.Password = PassWord;
                    ret.FullName = "";
                    ret.AppCode = AppCode;
                    userBO = new UserBO();

                    return userBO.RegisterUser(ret);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //su dung cho pm2
        public bool ResetPassWordByforget(string UserName, string Email, string AppCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return false;
                }
                else
                {
                    USER_GROUP_CREATE ret = new USER_GROUP_CREATE();
                    ret.UserName = UserName;
                    ret.Email = Email;
                    ret.AppCode = AppCode;
                    userBO = new UserBO();
                    PasswordGenerator gp = new PasswordGenerator();
                    gp.Minimum = 2;
                    gp.Maximum = 4;

                    gp.Kytuso = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
                    string a = gp.Generate();

                    gp.Kytuso = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
                    string a1 = gp.Generate();

                    gp.Kytuso = "0123456789".ToCharArray();
                    string a2 = gp.Generate();

                    gp.Kytuso = "!@$^-_()".ToCharArray();
                    string a3 = gp.Generate();

                    string PassWord = a + a1 + a2 + a3;

                    ret.Password = PassWord;
                    bool senmail = SendGmail(ret.Email, "Thông tin tài khoản", "UserName: " + ret.UserName + " -- Pass: " + ret.Password);

                    if (senmail == true)
                    {
                        bool Result = userBO.ResetPassWordByforget(ret);
                        if (Result == true)
                        {
                            return true;
                        }
                        else
                            return false;
                    }
                    else
                        return false;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }

        }

        public bool CheckPassUserName(string PassWord, string UserName, string AppCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return false;
                }
                else
                {
                    userBO = new UserBO();
                    string salt = userBO.GetPasswordSalt(UserName, AppCode);
                    bool success = userBO.Login(UserName, PassWord + salt, AppCode);
                    return success;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public bool CheckEmail(string Email, string AppCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return false;
                }
                else
                {
                    userBO = new UserBO();
                    bool success = userBO.CheckEmail(Email, AppCode);
                    return success;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public bool deleteUser(string UserName, string appCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return false;
                }
                else
                {
                    bool ret = userBO.deleteUser(UserName, appCode);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public UserInGroupUpdate UserInGroupUpdate(UserInGroupUpdate user)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new UserInGroupUpdate();
                }
                else
                {
                    UserInGroupUpdate ret = user;
                    if (!WebSecurity.Initialized)
                    {
                        WebSecurity.InitializeDatabaseConnection("DHQGHN_ADMIN.ConnectionString", "Users", "Id", "Username", autoCreateTables: false);
                    }
                    ret.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                    if (String.IsNullOrWhiteSpace(ret.UserName))
                    {
                        ret.ErrorCode = 1;
                        ret.ErrorMessage = Properties.Resources.MSG_USERNAME_EMPTY;
                        return ret;
                    }
                    if (!WebSecurity.UserExists(ret.UserName))
                    {
                        ret.ErrorCode = 2;
                        ret.ErrorMessage = Properties.Resources.MSG_USERNAME_NO_EXISTS;
                        return ret;
                    }
                    if (String.IsNullOrWhiteSpace(ret.GroupCode))
                    {
                        ret.ErrorCode = 3;
                        ret.ErrorMessage = Properties.Resources.MSG_GROUPCODE_EMPTY;
                        return ret;
                    }
                    if (groupBO.CheckGroupExist(ret.GroupCode) == false)
                    {
                        ret.ErrorCode = 4;
                        ret.ErrorMessage = Properties.Resources.MSG_GROUPCODE_NO_EXIST;
                        return ret;
                    }
                    if (String.IsNullOrWhiteSpace(ret.GroupCodeOld))
                    {
                        ret.ErrorCode = 5;
                        ret.ErrorMessage = Properties.Resources.MSG_GROUPCODE_NEW_EMPTY;
                        return ret;
                    }
                    if (groupBO.CheckGroupExist(ret.GroupCodeOld) == false)
                    {
                        ret.ErrorCode = 6;
                        ret.ErrorMessage = Properties.Resources.MSG_GROUPCODE_NEW_NO_EXIST;
                        return ret;
                    }
                    else
                    {
                        ret.ErrorCode = 200;
                    }
                    // string res = WebSecurity.CreateUserAndAccount(ret.UserName, "123456", new { ret.IsActive, ret.FullName }, false);
                    if (ret.ErrorCode == 200)
                    {
                        UserInGroupUpdate us = new UserInGroupUpdate();
                        us.UserName = user.UserName;
                        us.GroupCode = user.GroupCode;
                        us.GroupCodeOld = user.GroupCodeOld;
                        bool flag = userInGroupBO.UserInGroupUpdate(us);
                        if (flag)
                        {
                            ret.ErrorMessage = "SUCCESS";
                        }
                        else
                        {
                            ret.ErrorCode = -1;
                            ret.ErrorMessage = "ERROR";
                        }
                    }
                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //su dung tren PM2
        public UserInGroupUpdate UpdateUserInGroup(UserInGroupUpdate user)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new UserInGroupUpdate();
                }
                else
                {
                    UserInGroupUpdate ret = user;
                    ret.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                    if (String.IsNullOrWhiteSpace(ret.UserName))
                    {
                        ret.ErrorCode = 1;
                        ret.ErrorMessage = Properties.Resources.MSG_USERNAME_EMPTY;
                        return ret;
                    }

                    if (String.IsNullOrWhiteSpace(ret.GroupCode))
                    {
                        ret.ErrorCode = 3;
                        ret.ErrorMessage = Properties.Resources.MSG_GROUPCODE_EMPTY;
                        return ret;
                    }
                    if (groupBO.CheckGroupExist(ret.GroupCode, ret.AppCode) == false)
                    {
                        ret.ErrorCode = 4;
                        ret.ErrorMessage = Properties.Resources.MSG_GROUPCODE_NO_EXIST;
                        return ret;
                    }
                    if (String.IsNullOrWhiteSpace(ret.GroupCodeOld))
                    {
                        ret.ErrorCode = 5;
                        ret.ErrorMessage = Properties.Resources.MSG_GROUPCODE_NEW_EMPTY;
                        return ret;
                    }
                    if (groupBO.CheckGroupExist(ret.GroupCodeOld, ret.AppCode) == false)
                    {
                        ret.ErrorCode = 6;
                        ret.ErrorMessage = Properties.Resources.MSG_GROUPCODE_NEW_NO_EXIST;
                        return ret;
                    }
                    else
                    {
                        ret.ErrorCode = 200;
                    }
                    //20160127 - vanduong            
                    if (ret.ErrorCode == 200)
                    {
                        bool flag = userInGroupBO.UpdateGroup(ret);
                        if (flag)
                        {
                            ret.ErrorMessage = "SUCCESS";
                        }
                        else
                        {
                            ret.ErrorCode = -1;
                            ret.ErrorMessage = "ERROR";
                        }
                    }
                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public DAL.Models.Admin.UserModel Authenthication(DAL.Models.Admin.UserModel u)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new UserModel();
                }
                else
                {
                    userBO = new UserBO();
                    string salt = userBO.GetPasswordSalt(u.UserName, u.AppCode);
                    bool success = userBO.Login(u.UserName, u.Password + salt, u.AppCode);

                    if (success)
                    {
                        //Lay thong tin nguoi dung
                        DAL.Models.Admin.UserModel cUser = userBO.GetUserInfo(u.UserName, u.AppCode);
                        u.ID = cUser.ID;
                        u.FullName = cUser.FullName;
                        u.CountDay = cUser.CountDay;
                        u.IsActive = cUser.IsActive;
                        // u.ADM_UNIT_ID = cUser.ADM_UNIT_ID;
                        if (u.IsActive == null || u.IsActive <= 0)
                        {
                            //Kiem tra trang thai tai khoan
                            u.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                            u.ErrorCode = 1;
                            u.ErrorMessage = Properties.Resources.MSG_LOGIN_ACC_LOCKED;
                            u.LoginTime = u.LoginTime + 1;
                            return u;
                        }
                        else
                        {
                            //Kiem tra quyen truy cap cua tai khoan
                            bool permission = appBO.checkPermissionOfUser(u.ID, u.AppCode);
                            if (!permission)
                            {
                                u.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                                u.ErrorCode = 2;
                                u.ErrorMessage = Properties.Resources.MSG_LOGIN_CANNOT_ACCESS_APP;
                                u.LoginTime = u.LoginTime + 1;
                                return u;
                            }
                        }

                        //Lay danh sach menu duoc phan quyen
                        string appCode = u.AppCode;
                        u.ListMenu = getLisMenuByUserIdAndAppCode(u.ID, u.AppCode).ToList();

                        //Lay danh sach vai tro
                        u.ListRole = getListRoleByUserIdAndAppCode(u.ID, u.AppCode).ToList();

                        //Lay danh sach Nhom
                        u.ListGroup = getLisGroupByUserIdAndAppCode(u.ID, u.AppCode).ToList();
                        return u;
                    }
                    else
                    {
                        u.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                        u.ErrorCode = 3;
                        u.ErrorMessage = Properties.Resources.MSG_LOGIN_FAILED;
                        u.LoginTime = u.LoginTime + 1;
                        return u;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public T_Users pLogin(UserUpload user)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new  T_Users();
                }
                else
                {
                    string myAppCode = user.AppCode;
                    //===========================
                    T_Users ret = new T_Users();
                    user.AppCode = "TKTHDS.PM2";
                    //user.UserName = "dtv01";
                    //user.PassWord = "123456qR@";
                    //===========================

                    ret.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();

                    if (DHQGHN.Common.Utils.IsNullOrEmptyOverride(user.UserName))
                    {
                        ret.ErrorCode = -1;
                        ret.ErrorMessage = Properties.Resources.MSG_LOGIN_USERNAME_EMPTY;
                        ret.USERS = null;
                        return ret;
                    }
                    else if (DHQGHN.Common.Utils.IsNullOrEmptyOverride(user.PassWord))
                    {
                        ret.ErrorCode = -1;
                        ret.ErrorMessage = Properties.Resources.MSG_LOGIN_PASSWORD_EMPTY;
                        ret.USERS = null;
                        return ret;
                    }
                    else if (DHQGHN.Common.Utils.IsNullOrEmptyOverride(user.AppCode))
                    {
                        ret.ErrorCode = -1;
                        ret.ErrorMessage = Properties.Resources.MSG_LOGIN_APPCODE_EMPTY;
                        ret.USERS = null;
                        return ret;
                    }

                    DAL.Models.Admin.UserModel userRes = new DAL.Models.Admin.UserModel();
                    userRes.UserName = user.UserName;
                    userRes.Password = user.PassWord;
                    userRes.AppCode = user.AppCode;
                    userRes = Authenthication(userRes);

                    if (userRes != null)
                    {
                        //ret.ErrorCode = userRes.ErrorCode;
                        if (userRes.ErrorCode == 1 || userRes.ErrorCode == 2 || userRes.ErrorCode == 3)
                        {
                            ret.ErrorMessage = userRes.ErrorMessage;
                            ret.ErrorCode = userRes.ErrorCode;
                        }
                        else if (userRes.ErrorCode == 0)
                        {
                            ret.ErrorCode = 200;
                            string enumratorID = enumeratorBO.GetByUserName(userRes.UserName);

                            ret.ErrorMessage = "SUCCESS";

                            TabletUsers _user = new TabletUsers();

                            _user.USER_NAME = userRes.UserName;
                            _user.PASSWORD = "";
                            _user.PASSWORD_SALT = "";
                            _user.USER_TYPE = GetGroupCode(userRes.ListGroup);

                            if (_user.USER_TYPE == null)
                            {
                                ret.ErrorCode = -3;
                                ret.ErrorMessage = Properties.Resources.MSG_LOGIN_CANNOT_ACCESS_APP;
                                return ret;
                            }

                            if (string.IsNullOrEmpty(enumratorID))
                            {
                                _user.ENUMERATOR_ID = "";
                                ret.ENUMERATOR = new List<ENUMERATOR>();
                                ret.AREA_BOUNDPOINT = new List<AREA_BOUNDPOINT>();
                                ret.AREA = new List<AREA>();
                                ret.AREA_ENUM = new List<Area_Enum>();
                            }
                            else
                            {
                                _user.ENUMERATOR_ID = enumratorID;
                                ret.ENUMERATOR = commonListBO.GetEnumByIDandPID(_user.ENUMERATOR_ID);
                                ret.AREA_BOUNDPOINT = commonListBO.GetAreaBoundPointByEnum(_user.ENUMERATOR_ID);
                                ret.AREA = commonListBO.GetAreaByEnumID(_user.ENUMERATOR_ID);
                                ret.AREA_ENUM = commonListBO.GetAreaEnumByEnumID(_user.ENUMERATOR_ID);
                            }
                            ret.USERS = _user;
                        }

                        return ret;
                    }
                    else
                    {
                        ret.ErrorCode = -3;
                        ret.ErrorMessage = Properties.Resources.MSG_LOGIN_FAILED;
                        ret.USERS = null;
                        return ret;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new WebFaultException(System.Net.HttpStatusCode.BadRequest);
            }
        }
        #endregion

        public string GetGroupCode(List<GroupModel> groups)
        {
            if (groups != null && groups.Count() > 0)
            {
                foreach (GroupModel gr in groups)
                {
                    if ("DT".Equals(gr.GroupCode))
                    {
                        return gr.GroupCode;
                    }
                }

                foreach (GroupModel gr in groups)
                {
                    if ("BK".Equals(gr.GroupCode))
                    {
                        return gr.GroupCode;
                    }
                }
            }
            return null;
        }

        public IEnumerable<DAL.Models.Admin.MenuModel> GetAllMenuByUserIdAndAppCode(string userId, string appCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<DAL.Models.Admin.MenuModel>();
                }
                else
                {
                    return getLisMenuByUserIdAndAppCode(Convert.ToInt32(userId), appCode);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<DAL.Models.Admin.MenuModel> getLisMenuByUserIdAndAppCode(int userId, string appCode)
        {
            try
            {
                return new MenuBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_ADMIN_CONNECTION_STRING).GetAllMenuByUserIdAndAppCode(userId, appCode);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<DAL.Models.Admin.RoleModel> getListRoleByUserIdAndAppCode(int userId, string appCode)
        {
            try
            {
                return new RoleBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_ADMIN_CONNECTION_STRING).GetAllRoleByUserIdAndAppCode(userId, appCode);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<DAL.Models.Admin.GroupModel> getLisGroupByUserIdAndAppCode(int userId, string appCode)
        {
            try
            {
                return new GroupBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_ADMIN_CONNECTION_STRING).GetAllGroupByUserIdAndAppCode(userId, appCode);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public bool IsUnique(string UserName)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return false;
                }
                else
                {
                    bool ret = userBO.isUnique(UserName);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public List<DAL.Models.Admin.GroupModel> GroupGetAll(string AppCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<GroupModel>();;
                }
                else
                {
                    return groupBO.GetAllAppCode(AppCode);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public List<DAL.Models.Admin.CheckBoxList> GetGroupAllByUserName(string UserName, string AppCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<DAL.Models.Admin.CheckBoxList>();
                }
                else
                {
                    return groupBO.GetAllByUserName(UserName, AppCode);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public bool InsertUserIntoGroup(USER_GROUP_CREATE us)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return false;
                }
                else
                {
                    bool ret = userInGroupBO.InsertUserIntoGroup(us);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public List<ActionGroupCode> GetAllUserGroupCode(string GROUPCODE)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<ActionGroupCode>();
                }
                else
                {
                    return groupBO.GetAllUserGroupCode(GROUPCODE);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    //new FaultReason(string.Format("{0}", "Service fault exception")));
                    new FaultReason(string.Format("xx{0}", ex.Message)));
            }
        }

        public List<ActionNameModel> GetListActionName(string userName, string appId)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new  List<ActionNameModel>();
                }
                else
                {
                    return actionNameBO.GetListActionName(userName, appId);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("xx{0}", ex.Message)));
            }
        }

        public void actionCreateOrAddUser(DAL.Models.Admin.UserModel user)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();                    
                }
                else
                {
                    _UserBO = new UserBO();
                    _UserBO.CreateUser(user);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        public void actionCreateUserInGroupByListGroup(UserInListGroup ea)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    _UserBO = new UserBO();
                    _UserBO.actionCreateUserInGroupByListGroup(ea);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
    }
}